package cn.hamster3.mc.plugin.ball.bungee.api;

import cn.hamster3.mc.plugin.ball.bungee.HamsterBallPlugin;
import cn.hamster3.mc.plugin.ball.common.api.BallAPI;
import cn.hamster3.mc.plugin.ball.common.entity.BallServerType;
import cn.hamster3.mc.plugin.core.common.config.ConfigSection;
import cn.hamster3.mc.plugin.core.common.config.YamlConfig;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ListenerInfo;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.sql.SQLException;
import java.util.logging.Logger;

public class BallBungeeCordAPI extends BallAPI {
    public BallBungeeCordAPI(@NotNull ConfigSection config) {
        super(config, BallServerType.PROXY);
    }

    public static BallBungeeCordAPI getInstance() {
        return (BallBungeeCordAPI) instance;
    }

    public static void init(@NotNull File configFile) throws IOException {
        if (instance != null) {
            return;
        }
        YamlConfig config = YamlConfig.load(configFile);
        instance = new BallBungeeCordAPI(config);
    }

    @Override
    public void enable() throws SQLException, InterruptedException {
        for (ListenerInfo listenerInfo : ProxyServer.getInstance().getConfig().getListeners()) {
            if (!(listenerInfo.getSocketAddress() instanceof InetSocketAddress)) {
                continue;
            }
            InetSocketAddress address = (InetSocketAddress) listenerInfo.getSocketAddress();
            instance.getLocalServerInfo().setHost(address.getHostString());
            instance.getLocalServerInfo().setPort(address.getPort());
        }
        super.enable();
    }

    @Override
    public void disable() throws SQLException, InterruptedException {
        super.disable();
    }

    @Override
    public @NotNull Logger getLogger() {
        return HamsterBallPlugin.getInstance().getLogger();
    }
}
